import sys
import subprocess
import tarfile
import os
import logging
import pwd
import shutil  # 用于删除本地目录
from PyQt6.QtWidgets import QApplication, QDialog, QFileDialog, QInputDialog, QLineEdit
from ToolchainsUpdate.tools_update import Ui_Dialog  # 导入生成的 UI 类


class ToolUploader(QDialog):
    def __init__(self):
        super(ToolUploader, self).__init__()
        self.ui = Ui_Dialog()  # 创建 UI 实例
        self.ui.setupUi(self)  # 设置 UI

        # 连接按钮点击信号到处理方法
        self.ui.pushButton.clicked.connect(self.handleButtonClick)
        self.ui.pushButton_2.clicked.connect(self.handleButtonClick_2)
        self.ui.pushButton_3.clicked.connect(self.handleButtonClick_3)

    def handleButtonClick(self):
        self.ui.pushButton.setEnabled(False)  # 禁用按钮
        file_path, _ = QFileDialog.getOpenFileName(self, '选择 tar.gz 文件', '', 'Tar Files (*.tar.gz)')

        if file_path:
            self.ui.textEdit.append(f'选择的文件: {file_path}')
            self.uploadFile(file_path, "scripts/install_trosparser.sh", requires_sudo=False, chown_path=None)

        self.ui.pushButton.setEnabled(True)  # 启用按钮

    def handleButtonClick_2(self):
        self.ui.pushButton_2.setEnabled(False)  # 禁用按钮
        file_path, _ = QFileDialog.getOpenFileName(self, '选择 tar.gz 文件', '', 'Tar Files (*.tar.gz)')

        if file_path:
            self.ui.textEdit.append(f'选择的文件: {file_path}')
            self.uploadFile(file_path, "scripts/install_kvaser.sh", requires_sudo=True, chown_path=None)

        self.ui.pushButton_2.setEnabled(True)  # 启用按钮

    def handleButtonClick_3(self):
        self.ui.pushButton_3.setEnabled(False)  # 禁用按钮
        file_path, _ = QFileDialog.getOpenFileName(self, '选择 tar.gz 文件', '', 'Tar Files (*.tar.gz)')

        if file_path:
            self.ui.textEdit.append(f'选择的文件: {file_path}')
            self.uploadFile(file_path, "scripts/install_toolchains.sh", requires_sudo=True, chown_path=os.path.expanduser("~/toolchains"))

        self.ui.pushButton_3.setEnabled(True)  # 启用按钮

    def uploadFile(self, file_path, script_path, requires_sudo, chown_path=None):
        # 启用日志记录
        logging.basicConfig(level=logging.DEBUG)  # 设置日志级别
        logging.debug("Starting uploadFile method.")  # 添加调试信息

        extract_path = file_path.rstrip('.tar.gz')
        with tarfile.open(file_path, 'r:gz') as tar:
            tar.extractall(path=extract_path)
            self.ui.textEdit.append(f'解压到: {extract_path}')

        # 运行指定安装脚本并传递解压路径
        self.runInstallScript(script_path, extract_path, requires_sudo, chown_path)

    def runInstallScript(self, script_path, extract_path, requires_sudo, chown_path):
        logging.debug(f"Running install script: {script_path} with extract path: {extract_path}")

        # 获取当前用户信息
        current_user = os.getuid()
        current_user_info = pwd.getpwuid(current_user)
        username = current_user_info.pw_name
        groupname = current_user_info.pw_gid

        # 如果需要sudo权限，提示用户输入密码
        if requires_sudo:
            sudo_password, ok = QInputDialog.getText(self, 'Password Required', 'Enter sudo password:', echo=QLineEdit.EchoMode.Password)

            if not ok or not sudo_password:
                self.ui.textEdit.append('Error: No password provided')
                return

            # 使用 subprocess.Popen 执行 sudo 脚本，并通过 stdin 传递密码
            process = subprocess.Popen(
                f"echo {sudo_password} | sudo -E -S {script_path} {extract_path}",
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                bufsize=1
            )
        else:
            # 直接运行脚本
            process = subprocess.Popen(
                f"{script_path} {extract_path}",
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                bufsize=1
            )

        # 逐行读取输出并更新 UI
        for line in process.stdout:
            self.ui.textEdit.append(line.strip())
            self.ui.textEdit.ensureCursorVisible()  # 确保光标可见

        # 等待脚本执行完毕
        process.wait()
        if process.returncode != 0:
            error_message = process.stderr.read()
            self.ui.textEdit.append(f'脚本执行错误: {error_message.strip()}')
            logging.error(f"Script execution error: {error_message.strip()}")
        else:
            self.ui.textEdit.append('脚本执行完成')

            try:
                if os.path.exists(extract_path):
                    try:
                        shutil.rmtree(extract_path)  # 删除本地解压目录
                        self.ui.textEdit.append(f'删除本地解压目录: {extract_path}')
                    except Exception as e:
                        self.ui.textEdit.append(f'删除本地解压目录失败: {extract_path}, 错误: {str(e)}')
                        logging.error(f"Failed to delete local extraction directory: {extract_path}, error: {str(e)}")
                else:
                    self.ui.textEdit.append(f'本地解压目录不存在: {extract_path}')
            except Exception as e:
                self.output_signal.emit(f'脚本执行错误: {str(e)}')
                logging.error(f"Script execution error: {str(e)}")

            if requires_sudo and chown_path:
                # 更改指定路径的拥有者
                change_owner_command = f"echo {sudo_password} | sudo -E -S chown -R {username}:{groupname} {chown_path}"
                change_process = subprocess.run(change_owner_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

                if change_process.returncode != 0:
                    change_error_message = change_process.stderr.strip()
                    self.ui.textEdit.append(f'更改所有者错误: {change_error_message}')
                    logging.error(f"Change ownership error: {change_error_message}")
                else:
                    self.ui.textEdit.append(f'更改 {chown_path} 的所有者为 {username}:{groupname}.')
